import axios from 'axios';
import { Toast } from 'vant'

const instance = axios.create({
    baseURL: 'http://localhost:3000/',
    timeout: 12000,
    method: 'GET'
})

//http request 拦截器
instance.interceptors.request.use(
    config => {
        let headers = {
            //'Content-Type':'application/x-www-form-urlencoded',   // 传参方式表单
            'Content-Type': 'application/json;charset=UTF-8',        // 传参方式json
        };
        config.headers = headers
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//http response 拦截器
instance.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        const { response } = error;
        if (response) {
            return Promise.reject(response.data);
        } else {
            Toast.fail('网络连接异常,请稍后再试!');
        }
    }
);

// 封装 GET POST 请求并导出 默认post
/**
 * 
 * @param {请求地址} url 
 * @param {携带参数} params 
 * @param {请求方式} type 
 * @returns 
 */
export function request(url = '', params = {}, type = 'POST') {
    let token = localStorage.getItem('cookie');
    if (token) params.cookie = token;
    return new Promise((resolve, reject) => {
        let promise
        if (type.toUpperCase() === 'GET') {
            promise = instance({
                url,
                params
            })
        } else if (type.toUpperCase() === 'POST') {
            promise = instance({
                method: 'POST',
                url,
                data: params
            })
        }
        //处理返回
        promise.then(res => {
            // console.log(res, "ressssssssssss")
            let { data } = res
            if (data.code && data.code === 200) {
                resolve(res)
            }
        }).catch(err => {
            Toast(err.msg || "数据错误！")
            reject(err)
        })
    })
}
